# !/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from flask import Blueprint, request
from app.models.article import A10jqkaArticle
from app.util import get_tag, get_abstract
from app.util.response import resp_with_user, resp
from app.blueprint.user import is_login_by_session
from config import PALADIN

api = Blueprint('api', __name__)


@api.route('/page/', methods=['GET'])
@api.route('/page/<int:page_num>', methods=['GET'])
def page(page_num=1):
    article_page = A10jqkaArticle.query.order_by(A10jqkaArticle.publish_time.desc()).paginate(page_num, 20)
    return resp_with_user(data={
        'page': article_page.page,
        'pages': article_page.pages,
        'items': [{
            'title': article.title,
            'tag': get_tag(article.tag),
            'url': article.url,
            'content': get_abstract(article.content)
        } for article in article_page.items]
    })


@api.route('/paladin/', methods=['POST'])
def paladin():
    if not is_login_by_session():
        return resp(
            msg_id=-12
        )
    _d = request.get_json()
    _title = _d.get('title')
    _data = _d.get('data')
    _r_resp = requests.post(PALADIN, json={
        'title': _title,
        'data': _data
    })
    if _r_resp.status_code == 200:
        _rj = _r_resp.json()
        _rj['label'] = get_tag(_rj['label'])
        return resp(data=_rj)
    else:
        return resp(msg_id=-1000, status_code=_r_resp.status_code)
